import type { ISectionDetails, IUpdateSectionContentBody } from '@/interfaces';
import { useContext, useRef, useState } from 'react';
import useContentLayer from '@/hooks/useContentLayer';
import { SectionAdminContext } from '@/contexts/admin/forum/section';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import classNames from 'classnames';
import Editor from '@/app/[locale]/editor/wrapper';
import useToast from '@/hooks/useToast';
import { useMutation } from '@tanstack/react-query';
import type { TBody } from '@/types';
import { updateSectionContent } from '@/services/api';

export default function QuerySectionContent({
  details,
}: {
  details: ISectionDetails;
}) {
  const context = useContext(SectionAdminContext);
  const metadata = context.metadata!;
  const [previewContent, setPreviewContent] = useState(details.content || '');
  const { show } = useToast();
  const editorRef = useRef<{
    getEditorContent: () => string;
    setEditorContent: (value: any) => void;
  }>();
  const [type, setType] = useState(1);

  useContentLayer({
    dep: previewContent,
    metadata,
  });

  const updateSectionContentMutation = useMutation(
    async (variables: TBody<IUpdateSectionContentBody>) => {
      await updateSectionContent(variables);
    },
  );

  async function onClickSave() {
    try {
      const content = getEditorContent();
      if (!content) {
        show({
          type: 'SUCCESS',
          message: '保存完成',
        });
        return;
      }

      await updateSectionContentMutation.mutateAsync({
        id: details.basic.id,
        data: {
          content,
        },
      });

      show({
        type: 'SUCCESS',
        message: '保存完成',
      });
    } catch (e) {
      updateSectionContentMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function onClickPreview() {
    setType(1);
    setPreviewContent(getEditorContent());
  }

  async function onClickLoadEditor() {
    setType(2);
  }

  function getEditorContent() {
    const current = editorRef.current;
    if (!current) {
      return '';
    }
    return current.getEditorContent();
  }

  return (
    <div className="row">
      <div className="col">
        <div className="card">
          <div className="card-header bg-transparent text-muted">
            <i className="bi bi-card-text me-2"></i>
            内容
          </div>
          <div className="card-body vstack gap-4">
            <div className="ms-auto">
              <div
                className="btn-group"
                role="group"
                aria-label="编辑内容按钮组"
              >
                <button
                  onClick={onClickPreview}
                  type="button"
                  className={classNames('btn btn-primary', {
                    active: type === 1,
                  })}
                >
                  <i className="bi bi-book me-2"></i>
                  预览
                </button>

                <button
                  onClick={onClickLoadEditor}
                  type="button"
                  className={classNames('btn btn-primary', {
                    active: type === 2,
                  })}
                >
                  <i className="bi bi-pencil-square me-2"></i>
                  编辑
                </button>

                <button
                  onClick={onClickSave}
                  disabled={updateSectionContentMutation.isLoading}
                  type="button"
                  className={classNames('btn btn-primary', {
                    active: type === 3,
                  })}
                >
                  {updateSectionContentMutation.isLoading ? (
                    <span
                      className="spinner-border spinner-border-sm me-2"
                      role="status"
                      aria-hidden="true"
                    ></span>
                  ) : (
                    <i className="bi bi-save me-2"></i>
                  )}
                  保存
                </button>
              </div>
            </div>

            <div
              className={classNames({
                'd-none': type === 1,
                'd-block': type === 2,
              })}
            >
              <Editor
                id={details.basic.id}
                initialData={details.content}
                metadata={metadata}
                type="section"
                ref={editorRef}
              />
            </div>

            {type === 1 &&
              (previewContent && previewContent !== 'nodata' ? (
                <div
                  className="content-layer"
                  dangerouslySetInnerHTML={{ __html: previewContent }}
                ></div>
              ) : (
                <Nodata />
              ))}
          </div>
        </div>
      </div>
    </div>
  );
}
